package server_service

/**
* @author aFun
* @data 2025/4/11 08:39
* @email: afunaaa222@163.com / 1030935903
* @address: Guangdong University of Technology, China
 */

import (
	"camp_lucky_draw/entity"
	"camp_lucky_draw/server"
	"camp_lucky_draw/server/data"
	"encoding/json"
	"errors"
	"github.com/streadway/amqp"
	"slices"
)

func Do_get_cumulative_rewards(role *entity.Role, Args map[string]interface{}) error {
	tx := server.DB.Begin()
	if tx.Error != nil {
		return tx.Error
	}
	err := do_check_cumulative_rewards(
		role, Args,
		check_is_open,
		check_lev,
		filter_same,
		filter_token_cost,
		filter_gained,
		update_cumulative_rewards)
	if err != nil {
		tx.Rollback()
		return err
	}

	if err = tx.Save(&role).Error; err != nil {
		tx.Rollback()
		return err
	}

	tx.Commit()
	return err
}

func do_check_cumulative_rewards(role *entity.Role, Args map[string]interface{}, checks ...CheckFunc) error {
	for _, check := range checks {
		if err := check(role, Args); err != nil {
			return err
		}
	}
	return nil
}

// 重复领取过滤
func filter_same(role *entity.Role, Args map[string]interface{}) error {
	Index := Args["Index"].([]int64)
	NewIndex := []int64{}
	mp := make(map[int64]bool)
	for _, v := range Index {
		if !mp[v] {
			mp[v] = true
			NewIndex = append(NewIndex, v)
		}
	}
	Args["Index"] = NewIndex
	return nil
}

// 过滤不满足领取要求的
func filter_token_cost(role *entity.Role, Args map[string]interface{}) error {
	ld := role.Lucky_draw
	Consumed_tokens := ld.Consumed_tokens
	Index := Args["Index"].([]int64)
	NewIndex := []int64{}
	for _, index := range Index {
		if data.GetCumulativeRewards[index] == nil {
			continue
		}
		CfgCumulativeRewards := data.GetCumulativeRewards[index].(map[string]interface{})
		TokenCost := int64(CfgCumulativeRewards["tokenCost"].(float64))
		if Consumed_tokens >= TokenCost {
			NewIndex = append(NewIndex, index)
		}
	}
	Args["Index"] = NewIndex
	return nil
}

// 过滤领取过的
func filter_gained(role *entity.Role, Args map[string]interface{}) error {
	ld := role.Lucky_draw
	CumulativeRewards := ld.CumulativeRewarded
	Index := Args["Index"].([]int64)
	NewIndex := []int64{}
	for _, index := range Index {
		if !slices.Contains(CumulativeRewards, index) {
			NewIndex = append(NewIndex, index)
		}
	}
	Args["Index"] = NewIndex
	return nil
}

// 奖励发放
func update_cumulative_rewards(role *entity.Role, Args map[string]interface{}) error {
	Index := Args["Index"].([]int64)
	if len(Index) == 0 {
		return errors.New("没有可领取的奖励")
	}
	ld := role.Lucky_draw
	ld_cr := ld.CumulativeRewarded
	Items := []entity.Item{}
	ItemQs := []entity.ItemForQueue{}
	for _, index := range Index {
		// 更新活动结构数据
		ld_cr = append(ld_cr, index)

		// 更新角色背包数据
		CfgCumulativeRewards := data.GetCumulativeRewards[index].(map[string]interface{})
		item := entity.Item{
			Id:   int64(CfgCumulativeRewards["itemId"].(float64)),
			Num:  int64(CfgCumulativeRewards["quantity"].(float64)),
			Name: CfgCumulativeRewards["itemName"].(string),
		}
		Items = append(Items, item)
		itemQ := entity.ItemForQueue{
			Role_id: role.ID,
			Id:      int64(CfgCumulativeRewards["itemId"].(float64)),
			Num:     int64(CfgCumulativeRewards["quantity"].(float64)),
			Name:    CfgCumulativeRewards["itemName"].(string),
		}
		ItemQs = append(ItemQs, itemQ)
	}
	ld.CumulativeRewarded = ld_cr
	role.Lucky_draw = ld
	role.Bags = append(role.Bags, Items...)

	ch, _ := server.MQ.Channel()
	defer ch.Close()
	for _, iq := range ItemQs {
		body, _ := json.Marshal(iq)
		_ = ch.Publish(
			"",
			"rewards_update",
			false,
			false,
			amqp.Publishing{
				ContentType: "application/json",
				Body:        body,
			})
	}
	return nil
}
